<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
      label-width="120px">
      <el-form-item prop="name" label="专业名称">
        <el-input v-model="dataForm.name" placeholder="专业名称"></el-input>
      </el-form-item>
      <el-form-item prop="description" label="专业介绍">
        <el-input v-model="dataForm.description" placeholder="专业介绍" type="textarea"></el-input>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  import { reactive, ref } from "vue";
  import baseService from "@/service/baseService";
  import { isEmail, isMobile } from "@/utils/utils";
  import { IObject } from "@/types/interface";
  import { ElMessage } from "element-plus";
  const emit = defineEmits(["refreshDataList"]);
  const visible = ref(false);
  const dataFormRef = ref();

  const dataForm = reactive({
    id: '',
    name: "",
    description: "",
  });

  const rules = ref({
    name: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  });

  const init = (value?: Object) => {
    visible.value = true;

    if (value && value.id) {
      dataForm.id = value.id;
      dataForm.name = value.name;
      dataForm.description = value.description;
    } else {
      dataFormRef.value.resetFields();
      dataForm.id = '';
      dataForm.name = '';
      dataForm.description = '';
    }
  };

  // 表单提交
  const dataFormSubmitHandle = () => {
    dataFormRef.value.validate((valid: boolean) => {
      if (!valid) {
        return false;
      }
      if (!dataForm.id) {
        baseService.post("/cam/major/create", {
          ...dataForm,
        }).then((res) =>
          ElMessage.success({
            message: "成功",
            duration: 500,
            onClose: () => {
              visible.value = false;
              emit("refreshDataList");
            }
          }))
      }
      else {
        baseService.put("/cam/major/update", {
          ...dataForm,
        }).then((res) =>
          ElMessage.success({
            message: "成功",
            duration: 500,
            onClose: () => {
              visible.value = false;
              emit("refreshDataList");
            }
          }))
      }
    });
  };

  defineExpose({
    init
  });
</script>

<style lang="less" scoped>
  .mod-sys__user {
    .role-list {
      .el-select {
        width: 100%;
      }
    }
  }
</style>